<?php


namespace app\api\controller\activity;


use addons\xyb\XypHelper;
use app\api\controller\xyb\Base;

use app\api\service\UsersService;


class Advertisement extends Base
{
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function index()
    {
        if(!$position_id = (int)$this->request->request('id')){
            $this->error('参数错误');
        }
        $position_model = model('app\admin\model\AdvertisementPosition');
        $position = $position_model->where('id', $position_id)->find();
        if(!$position || $position->status != 1){
            $this->success('请求成功', ['height' => 0, 'list' => []]);
        }
        $users = $this->getAuthUsers();
        $user_id = $users->id;
        $user_circle = UsersService::formatUsersCircleStatusInfo($users->id, $users->circle_id);
        $circle_id = (isset($user_circle['circle_id'])?$user_circle['circle_id']:0);
        // 获取广告位列表
        $list = model('app\common\model\marketing\Advertisement')
            ->where(['status' => 1, 'position' => $position_id])
            ->field('id,name,image,jump_method,jump_app,jump_url,jump_route,height')
            ->where(function ($query) use ($user_id, $circle_id) {
                if($circle_id && $user_id){
                    $query->where('grant_method', 1)->whereOr(function ($q) use ($circle_id) {
                        $q->where('grant_method', 2)->whereRaw("FIND_IN_SET('{$circle_id}', grant_agent_id)");
                    })->whereOr(function ($q) use ($user_id) {
                        $q->where('grant_method', 3)->whereRaw("FIND_IN_SET('{$user_id}', grant_users_id)");
                    });
                } else {
                    $query->where('grant_method', 1);
                }
            })
            ->order('weigh desc, id desc')
            ->select();
        
        // 处理跳转参数
        foreach ($list as &$item) {
            $item['image'] = cdnurl($item['image'], true);
            if($item['jump_method'] == 'page'){
                $item['jump_url'] = XypHelper::formatJsonStringToArray($item['jump_route'],'page');
            }
        }

        $this->success('请求成功', ['height' => ($position->height?$position->height:70), 'list' => $list]);
    }

}